﻿using Jupiter.Infrastructure.Attributes;
using Jupiter.Infrastructure.Cache.Interfaces;
using Jupiter.Infrastructure.Domain.SqlSugar;
using Jupiter.Infrastructure.Domain.SqlSugar.Basic;
using Jupiter.Infrastructure.Exceptions;
using Jupiter.Infrastructure.Mappings;
using Jupiter.Infrastructure.Permission;
using Jupiter.Infrastructure.Permission.DataPermissions;
using Jupiter.Infrastructure.Responses;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Localization;
using Wips.AppService.Publisher;
using Wips.AppService.Publisher.Models;
using Wips.AppService.Publisher.Requests;
using Wips.Domain.Models;
using Wips.Infrastructure.Model;

namespace Wips.AppService.SqlSugar.Publisher
{
    /// <summary>
    /// 子服务查询
    /// </summary>
    [ServiceComponent]
    public class AgentServerAppService : AppServiceQueryBase<AgentServer>, IAgentServerAppService
    {
        private readonly IMapsterMapper _mapsterMapper;
        private readonly PublishMasterService _publishMasterService;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="securityContextAccessor"></param>
        /// <param name="configuration"></param>
        /// <param name="cacheManager"></param>
        /// <param name="permission"></param>
        /// <param name="stringLocalizer"></param>
        public AgentServerAppService(ISqlSugarClient dbContext,
            ISecurityContextAccessor securityContextAccessor, IConfiguration? configuration, ICacheManager? cacheManager, IDataPermission? permission, IStringLocalizer? stringLocalizer, IMapsterMapper mapsterMapper, PublishMasterService publishMasterService) : base(dbContext, securityContextAccessor, configuration, cacheManager, permission, stringLocalizer)
        {
            _mapsterMapper = mapsterMapper;
            _publishMasterService = publishMasterService;
        }


        /// <summary>
        /// 获取注册的服务
        /// </summary>
        /// <returns></returns>
        public async Task<PageResult<AgentServerModel>> GetPageAsync(GetAgentServerPageRequest request)
        {

            var list = await Query()
                .Select<AgentServerModel>()
                .ToPageAsync(request);
            return list;
        }

        /// <summary>
        /// 获取单条子服务器信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="CoreException"></exception>
        public async Task<AgentServerConfigModel> GetByIdAsync(string id)
        {
            var item = await Query<AgentServerConfig>()
                .Includes(c => c.AgentServer)
                .Where(c => c.Id == id).FirstAsync();
            if (item == null)
            {
                throw new CoreException("未找到对应子服务器");
            }
            var result = _mapsterMapper.MapTo<AgentServerConfigModel>(item);
            result.UploadPath = Wips.Infrastructure.Consts.MapUploadZipFile;
            return result;
        }


        /// <summary>
        /// 健康检查
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> CheckHealthyAsync(string id)
        {


            var item = await Query().Where(c => c.Id == id).Select(c => new { c.Id, c.AgentAddress }).FirstAsync();

            var result = await _publishMasterService.HealthyCheckAsync(item.AgentAddress);

            return result.ToLower() == "ok";
        }
        /// <summary>
        /// 获取子服务的配置的分页
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PageResult<AgentServerConfigModel>> GetAgentServerConfigsAsync(GetAgentServerConfigPageRequest request)
        {
            var list = await Query<AgentServerConfig>()
                .Where(c => c.AgentServerId == request.AgentServerId)
                .Select<AgentServerConfigModel>()
                .ToPageAsync(request);



            return list;
        }


        /// <summary>
        /// 获取子服务器的盘符
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="CoreException"></exception>
        public async Task<List<string>> GetAgentRootPath(string id)
        {

            var agent = await Query().Where(c => c.Id == id).Select(c => new { c.Id, c.AgentAddress }).FirstAsync();
            if (agent == null)
            {
                throw new CoreException("未找到对应子服务器");
            }
            try
            {
                var result = await _publishMasterService.GetRootPathAsync(agent.AgentAddress);
                if (result.Success)
                {
                    return result.Data!;
                }
                else
                {
                    throw new CoreException(result.Message);
                }

            }
            catch (Exception ex)
            {

                Console.WriteLine(ex);
                throw new CoreException(ex.Message);
            }

        }

        /// <summary>
        /// 获取子服务器的文件夹 by目录
        /// </summary>
        /// <param name="id"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        /// <exception cref="CoreException"></exception>
        public async Task<List<DirectoryModel>> GetDirectoryAsync(string id, string path)
        {
            var agent = await Query().Where(c => c.Id == id).Select(c => new { c.Id, c.AgentAddress }).FirstAsync();
            if (agent == null)
            {
                throw new CoreException("未找到对应子服务器");
            }
            try
            {
                var result = await _publishMasterService.GetFolderListAsync(agent.AgentAddress, path);
                if (result.Success)
                {
                    return result.Data!;
                }
                else
                {
                    throw new CoreException(result.Message);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw new CoreException(ex.Message);
            }

        }

        /// <summary>
        /// 获取文件文本内容
        /// </summary>
        /// <param name="id"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        /// <exception cref="CoreException"></exception>
        public async Task<string> GetFileTextAsync(string id, string path)
        {

            var agent = await Query().Where(c => c.Id == id).Select(c => new { c.Id, c.AgentAddress }).FirstAsync();
            if (agent == null)
            {
                throw new CoreException("未找到对应子服务器");
            }
            try
            {
                var result = await _publishMasterService.GetFileTextAsync(agent.AgentAddress, path);
                if (result.Success)
                {
                    return result.Data!;
                }
                else
                {
                    throw new CoreException(result.Message);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw new CoreException(ex.Message);
            }
        }



        /// <summary>
        /// 执行备份
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="CoreException"></exception>
        public async Task<string> BackupAsync(BackupRequest request)
        {


            var agent = await Query<AgentServerConfig>()
                .Includes(c => c.AgentServer)
                .Where(c => c.Id == request.Id).FirstAsync();
            if (agent == null)
            {
                throw new CoreException("未找到对应子服务器");
            }
            try
            {
                request.Key = request.Id;
                request.UserId = UserId;
                var result = await _publishMasterService.BackUpAsync(agent.AgentServer!.AgentAddress, request);
                if (result.Success)
                {
                    return result.Data!;
                }
                else
                {
                    throw new CoreException(result.Message);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw new CoreException(ex.Message);
            }
        }




        /// <summary>
        /// 获取级联数据
        /// </summary>
        /// <returns></returns>
        public async Task<List<CascaderModel>> GetCascaderAsync()
        {


            // 获取我的权限
            var permission = await Query<AgentServerPermission>()
                .Where(c => c.UserId == UserId)
                .ToListAsync();
            var agentServerIds = permission.Select(c => c.AgentServerId).ToList();
            var agentServerConfigIds = permission.Select(c => c.AgentServerConfigId).ToList();

            var list = await Query()
                .Includes(c => c.AgentServerConfigs)

                 .ToListAsync();


            var result = list
                .Where(c => agentServerIds.Contains(c.Id) ||
                 c.AgentServerConfigs!.Any(x => agentServerConfigIds.Contains(x.Id))
                )
                .Select(c => new CascaderModel
                {
                    Children = c.AgentServerConfigs!
                 .Where(x => agentServerIds.Contains(x.AgentServerId)
                 || agentServerConfigIds.Contains(x.Id)
                 )
                .Select(x => new CascaderModel
                {
                    Label = x.ServerName,
                    Value = x.Id
                }).ToList(),
                    Label = c.ServerName + "[" + c.ServerKey + "]",
                    Value = c.Id!
                }).ToList();

            return result;


        }



    }




}